extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

#include <iostream>
using namespace std;

class CCounter {
    CCounter():m_(0){}
    int count() {return ++m_;}
private:
    int m_;
};

int count(lua_State *L)
{
    double m_ = lua_tonumber(L, lua_upvalueindex(1));
    lua_pushnumber(L, ++m_);
    lua_replace(L, lua_upvalueindex(1));
    lua_pushvalue(L, lua_upvalueindex(1));
    return 1;
}

int newCount(lua_State *L)
{
    lua_pushnumber(L,0);
    lua_pushcclosure(L, count, 1);
    return 1;
}

int main()
{
    char *szLua_code = "c1 = NewCount() "
                       "c2 = NewCount() "
                       "for i=1,5 do print(c1()) end "
                       "for i=1,5 do print(c2()) end ";

    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    lua_register(L, "NewCount", newCount);

    bool err = luaL_loadstring(L, szLua_code) || lua_pcall(L,0,0,0);
    if (err)
    {
        cerr << lua_tostring(L, -1);
        lua_pop(L, 1);
    }

    lua_close(L);
    return 0;
}

